#include "timer_widget.h"
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QTimerEvent>
#include <QDebug>

TimerWidget::TimerWidget(QWidget *parent)
	: QWidget{parent}
{
	QVBoxLayout * mainLayout=new QVBoxLayout();
	// 标签
	QWidget * LabelWidget=new QWidget();
	L1=new QLabel(LabelWidget);
	L1->setStyleSheet("background-color: red;");
	L1->setFixedSize(50,50);
	L1->move(0,20);
	L2=new QLabel(LabelWidget);
	L2->setStyleSheet("background-color:green;");
	L2->setFixedSize(50,50);
	L2->move(0,80);


	// 按钮
	QHBoxLayout * btnLayout=new QHBoxLayout();
	QPushButton * start=new QPushButton("开始");
	connect(start,&QPushButton::clicked,this,&TimerWidget::start);
	QPushButton * stop=new QPushButton("停止");
	connect(stop,&QPushButton::clicked, this, &TimerWidget::stop);
	QPushButton * reset=new QPushButton("复位");
	connect(reset, &QPushButton::clicked, this, &TimerWidget::reset);

	btnLayout->addWidget(start);
	btnLayout->addWidget(stop);
	btnLayout->addWidget(reset);

	mainLayout->addWidget(LabelWidget);
	mainLayout->addLayout(btnLayout);
	this->setLayout(mainLayout);
}

void TimerWidget::start()
{
	if(id1 ==0 && id2==0){
		id1 = this->startTimer(10);
		id2 = this->startTimer(20);
	}
}

void TimerWidget::stop()
{
	this->killTimer(id1);
	this->killTimer(id2);
	id1=id2=0;
}

void TimerWidget::reset()
{
	this->stop();
	L1->move(0,L1->y());
	L2->move(0,L2->y());
}

void TimerWidget::timerEvent(QTimerEvent *event)
{
	if(event->timerId() == id1){
		L1->move(L1->x() + 1,L1->y());
		if(L1->x() >= this->width()){
			L1->move(0,L1->y());
		}
	}else if(event->timerId() == id2){
		L2->move(L2->x() + 1,L2->y());
		if(L2->x() >= this->width()){
			L2->move(0,L2->y());
		}
	}else{
		qDebug() << event->timerId();
	}
}

